import argparse
import time

import tkinter as tk
from chat_server import init_server,init_client

input_ls = []
global_list = None
list_count = 1

def init_gui():
    global global_list
    root = tk.Tk()
    
    frm = tk.Frame(master=root,width=2000, height=1000)
    frm.grid(column=1, row=0)
    tk.Label(frm, text="聊天记录:").pack()
    chat_list = tk.Listbox(frm)
    frm.grid(column=2, row=0)
    chat_list.pack()
    frm.grid(column=3, row=0)
    input_box = tk.Entry(frm)
    input_box.pack()
    def keyHandler(event):
        #发送输入框的内容
        input_ls.append(input_box.get())
        input_box.delete(0,"end")

    frm.grid(column=4, row=0)
    input_box.bind("<Return>",keyHandler)
    tk.Button(frm, text="Quit", command=root.destroy).pack()

    global_list = chat_list
    frm.pack()
    root.mainloop()

def send_chat_list(msg):
    global global_list,list_count
    if global_list is not None:
        global_list.insert(list_count,msg)
        list_count += 1

def get_input_msg():
    while not input_ls:
        time.sleep(1)
    return input_ls.pop()


if __name__=='__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--name')
    parser.add_argument('--ip')
    args = parser.parse_args()

    if args.ip is None:
        init_server()
        init_client("localhost",get_input_msg,send_chat_list,args.name)
    else:
        init_client(args.ip,get_input_msg,send_chat_list,args.name)

    init_gui()        